package com.lostad.app.vert;

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import com.lostad.app.vert.api.verticle.ProductConsumer;
import com.lostad.app.vert.api.verticle.ProductSender;
import com.lostad.app.vert.util.AppProperties;
import com.lostad.app.vert.util.Runner;
import com.lostad.app.vert.web.WebVerticle;
import com.lostad.app.vert.websocket.WebSocketVerticle;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServer;
import io.vertx.ext.web.Router;

/**
 * This is an example application to showcase the usage of Vert.x Web.
 *
 * In this application you will see the usage of:
 *
 *  * Freemarker templates
 *  * Vert.x Web
 *
 * @author <a href="mailto:pmlopes@gmail.com>Paulo Lopes</a>
 */
public class MainVerticle extends AbstractVerticle {
///////////////////////////////////////////////////////////////////
// Convenience method so you can run it in your IDE
  public static void main(String[] args) {
	//这里是为了在ide中运行加的入口方法，要指定正确的web.dir
    int port = AppProperties.getValue("http.port", 8080);
    String webDir =  AppProperties.getValue("web.dir");
    System.out.println("###############port"+port);
    System.out.println("###############web.dir"+webDir);
    Runner.runExample(MainVerticle.class);
  }
/////////////////////////////////////////////////////////////////////
  @Override
  public void start(Future<Void> fut) throws Exception {
    final HttpServer server = vertx.createHttpServer();
    final Router router = Router.router(vertx);
    //初始化spring配置
    final ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class);
    final DeploymentOptions options = new DeploymentOptions().setInstances(8);//根据需要可以指定verticle实例的数量：启用多核支持
    //=============================================================================
     vertx.deployVerticle(new ProductSender(router)); //发布消息消费者
     vertx.deployVerticle(new ProductConsumer(context)); //发布消息消费者
    //=============================================================================== 
     vertx.deployVerticle(new WebSocketVerticle(server));//websocket
     vertx.deployVerticle(new WebVerticle(router),options);//web
    //===============================================================================
    
    // start a HTTP web server on port 9000 ，vertx-app.properties
    int port =  AppProperties.getValue("http.port",8080);
    System.out.println("--------------port"+port);
    server.requestHandler(router::accept).listen(port,result -> {
          if (result.succeeded()) { //Future 参数是非常重要的，可以通知是否已经执行完成。
            fut.complete();
          } else {
            fut.fail(result.cause());
          }
        });
  }
}